<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" value-key="supplierId" @change="changeSelect" placeholder="请选择供应商" clearable>
          <el-option
            v-for="dict in selectList"
            :key="dict.supplierId"
            :label="dict.supplierName"
            :value="dict"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单时间">
        <el-date-picker
          v-model="daterangePurchaseDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="编号" prop="purchaseSn">
        <el-input
          v-model="queryParams.purchaseSn"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="purchaseState">
        <el-select v-model="queryParams.purchaseState" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.purchase_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合计总金额" prop="purchaseTotal">
        <NumberBetween v-model="daterangePurchaseTotal"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['webshop:GoodsPurchase:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['webshop:GoodsPurchase:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['webshop:GoodsPurchase:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['webshop:GoodsPurchase:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GoodsPurchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单主键" align="center" prop="purchaseId"/>
      <el-table-column label="供应商" align="center" prop="supplierName"/>
      <el-table-column label="订单时间" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" prop="purchaseSn"/>
      <el-table-column label="说明" align="center" prop="purchaseInfo"/>
      <el-table-column label="合计总金额" align="center" prop="purchaseTotal"/>
      <el-table-column label="订单状态" align="center" prop="purchaseState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.purchase_state" :value="scope.row.purchaseState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['webshop:GoodsPurchase:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['webshop:GoodsPurchase:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择供应商" clearable>
            <el-option
              v-for="dict in selectList"
              :key="dict.supplierId"
              :label="dict.supplierName"
              :value="dict.supplierId"
            />
          </el-select>
          <el-button type="primary" @click="selectSku" :disabled="disabled">选择商品</el-button>
        </el-form-item>
        <el-form-item label="订单时间" prop="purchaseDate">
          <el-date-picker clearable
                          v-model="form.purchaseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择订单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="编号" prop="purchaseSn">
          <el-input v-model="form.purchaseSn" placeholder="请输入编号"/>
        </el-form-item>
        <el-form-item label="说明" prop="purchaseInfo">
          <el-input v-model="form.purchaseInfo" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="合计总金额" prop="purchaseTotal" v-if="form.purchaseId!=null">
          <el-input v-model="form.purchaseTotal" placeholder="请输入合计总金额"/>
        </el-form-item>
        <el-form-item label="订单状态" prop="purchaseState" v-if="form.purchaseId!=null">
          <el-radio-group v-model="form.purchaseState">
            <el-radio
              v-for="dict in dict.type.purchase_state"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <SelectSku ref="selectSku" v-if="shouSelectSku"/>

  </div>
</template>

<script>
import {
  checkPurchaseSn,
  listGoodsPurchase,
  getGoodsPurchase,
  delGoodsPurchase,
  addGoodsPurchase,
  updateGoodsPurchase
} from "@/api/webshop/GoodsPurchase";
import {listSupplierInfoSelect} from "@/api/webshop/SupplierInfo.js"
import NumberBetween from "@/components/ACPMTS/NumberBetween";
import SelectSku from "./SelectSku.vue";



export default {
  name: "GoodsPurchase",
  dicts: ['purchase_state'],

  components: {NumberBetween,SelectSku},
  data() {
    return {
      dialogVisible: false,
      shouSelectSku: false,
      selectList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      GoodsPurchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 订单状态时间范围
      daterangePurchaseDate: [],
      daterangePurchaseTotal: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
        purchaseDate: null,
        purchaseSn: null,
        purchaseState: null
      },
      // 表单参数
      form: {
        purchaseId: null,
        supplierId: null,
        purchaseDate: null,
        purchaseSn: null,
        purchaseInfo: null,
        purchaseTotal: null,
        purchaseState: null
      },
      // 表单校验
      rules: {
        purchaseSn: [
          {required: true, message: "编号不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('编号不能为空'));
              }
              checkPurchaseSn(value.trim()).then(res => {
                if (res.data) {
                  callback(new Error('编号已存在'));
                } else {
                  callback();
                }
              })

            }, trigger: 'blur'
          }
        ]
      },

      disabled: true
    };

  }
  ,
  created() {
    this.getList();
    this.getSelectList()
  },
  watch:{
    "form.supplierId": {
      handler(val) {
        this.disabled = !val;
      }
    }
  },
  methods: {
    changeSelect() {

    },
    selectSku() {
      console.log(this.form.supplierId)
      this.shouSelectSku = true;
      this.$nextTick(() => {
        this.$refs.selectSku.init = this.form.supplierId,this.form.supplierName;
      })
    },
    getSelectList() {
      listSupplierInfoSelect().then(response => {
        this.selectList = response.data;
      });
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangePurchaseDate && '' != this.daterangePurchaseDate) {
        this.queryParams.params["beginPurchaseDate"] = this.daterangePurchaseDate[0];
        this.queryParams.params["endPurchaseDate"] = this.daterangePurchaseDate[1];
      }
      if (null != this.daterangePurchaseTotal && '' != this.daterangePurchaseTotal) {
        this.queryParams.params["beginPurchaseTotal"] = this.daterangePurchaseTotal[0];
        this.queryParams.params["endPurchaseTotal"] = this.daterangePurchaseTotal[1];
      }
      listGoodsPurchase(this.queryParams).then(response => {
        this.GoodsPurchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: null,
        supplierId: null,
        purchaseDate: null,
        purchaseSn: null,
        purchaseInfo: null,
        purchaseTotal: null,
        purchaseState: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePurchaseDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseId = row.purchaseId || this.ids
      getGoodsPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseId != null) {
            updateGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + purchaseIds + '"的数据项？').then(function () {
        return delGoodsPurchase(purchaseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('webshop/GoodsPurchase/export', {
        ...this.queryParams
      }, `GoodsPurchase_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
